package com.pbase.tools;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by Apple on 15/12/17.
 */
public class JsonParser {

    public static String getStringValueByKey(JSONObject json, String key,
                                             String def) {
        try {
            if (!json.isNull(key)&&json.has(key))
                return json.getString(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }

    public static int getIntValueByKey(JSONObject json, String key, int def) {
        try {
            if (!json.isNull(key))
                return json.optInt(key, def);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }

    public static long getLongValueByKey(JSONObject json, String key, long def) {
        try {
            if (!json.isNull(key))
                return json.optLong(key, def);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }

    public static double getDoubleValueByKey(JSONObject json, String key,
                                             float def) {
        try {
            if (!json.isNull(key))
                return json.optDouble(key, def);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }

    public static boolean getBooleanValueByKey(JSONObject json, String key,
                                             boolean def) {
        try {
            if (!json.isNull(key))
                return json.optBoolean(key, def);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return def;
    }
    public static JSONArray getJsonArrayByKey(JSONObject json, String key) {
        try {
            if (!json.isNull(key))
                return json.optJSONArray(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject getJsonObjectBykey(JSONObject json, String key) {
        try {
            if (!json.isNull(key))
                return json.optJSONObject(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
